﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YuFeng.Services.User;
using YuFeng.Web.Areas.Admin.Models;
using YuFeng.Web.Filters;

namespace YuFeng.Web.Areas.Admin.Controllers
{
    [NormalAuthFilter]
    public class AuthController : Controller
    {

        private readonly IUserService _userService;
        public AuthController(IUserService userService)
        {
            _userService = userService;
        }

        [AllowAnonymous]
        public ActionResult Logon()
        {
            UserLoginViewModel userVm = new UserLoginViewModel();
            return View(userVm);
        }

        [HttpPost]
        [AllowAnonymous]
        public ActionResult Logon(UserLoginViewModel vm)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    vm.Password = YuFeng.Web.Helpers.SecurityHelper.MD5Encrypt(vm.Password);
                    var re = _userService.UserLogin(vm.Name, vm.Password);
                    if (re == null)
                    {
                        throw new Exception("登陆失败，验证失败！");
                    }
                    SessionContext.SignIn(re);

                    if (Request.IsAjaxRequest())
                    {
                        return Json(new { Result = true, Message = "登录成功！", Url = "/admin/home/index" });
                    }
                    else
                    {
                        return Redirect("Logon");
                    }
                }
                else
                {
                    if (Request.IsAjaxRequest())
                    {
                        return Json(new { Result = false, Message = "登陆失败，验证失败！" });
                    }
                    else
                    {
                        return View(vm);
                    }
                }
            }
            catch (Exception e)
            {
                if (Request.IsAjaxRequest())
                    return Json(new { Result = false, Message = e.Message });
                else
                    return View(vm);
            }
        }

        public ActionResult Logout()
        {
            SessionContext.SignOut();
            return Redirect("Logon");
        }
    }
}